<template>
  <div id="list">
      <button @click="toAdd">添加</button>
    <el-table :data="user_list" border style="width:40%;margin:40px auto;">
      <el-table-column fixed prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="姓名" width="80"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column  label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="toEdit(scope.row)" type="text" size="small">编辑</el-button>
          <el-button type="text" size="small" @click="toDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
    <el-form ref="user" :model="item" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="item.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model="item.age"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveUser">保存</el-button>
        <el-button type="primary" @click="resetItem">取消</el-button>
      </el-form-item>
    </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
        user_list:[],
        base_url:process.env.VUE_APP_BASEURL,
        item:{
            id:0,
            name:'',
            age:''
        },
        dialogVisible:false
    };
  },
  methods: {
      resetItem(){
          this.item = {
              id:0,
              name:'',
              age:''
          };
          this.dialogVisible = false;
      },
      toAdd(){
          this.resetItem();
          this.dialogVisible = true;
      },
      toEdit(el){
          this.item = el;
          this.dialogVisible = true;
      },
      saveUser(){
          axios.post(this.base_url + '/users',this.item,{headers:{token:localStorage.getItem('token')}}).then(res => {
            console.log(res.data);
            this.user_list = res.data.data;
            this.resetItem();
          });
      },
      toDel(id){
          axios.get(this.base_url + `/users/${id}`,{headers:{token:localStorage.getItem('token')}}).then(res => {
              console.log(res.data);
              this.user_list = res.data.data;
          });
      },
      getList(){
            console.log(this.base_url);
            axios.get(this.base_url + '/list',{headers:{token:localStorage.getItem('token')}}).then(res => {
                console.log(res.data)
                if(res.data.code == 2000){
                    this.user_list = res.data.data;
                }else{
                    console.log(res.data.msg);
                }
            });
      }
  },
  mounted() {
      this.getList();
  },
};
</script>

<style>
</style>
